﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using HtmlAgilityPack;
using Windstamp.Utility.BookDownload.Common;
using Windstamp.Utility.BookDownload.Entity;

namespace Windstamp.Utility.BookDownload.Core {
	/// <summary>
	/// 主页面
	/// </summary>
	class MainPage {
		/// <summary>
		/// 主页面的实体
		/// </summary>
		public MainPageInfo Info { get; set; }

        private string domain;

		/// <summary>
		/// 主页面
		/// </summary>
		/// <param name="url">主页面的 Url</param>
		public MainPage(string url) {
			Info = new MainPageInfo() {
				Url = url,
				Cookies = new CookieCollection()
			};
            domain = GetDoman(url);
            //domain = "http://www.wenhuakxjyty.cn";
		}

        private string GetDoman(string urlStr) {
            Uri url = new Uri(urlStr);
            return "http://" + url.Host;
        }

		/// <summary>
		/// 解析主页面数据Cookies和页面内容
		/// </summary>
		public void AnalyzeMainPage() {
			var request = UrlRequestHelper.BuildRequest(Info.Url, "utf-8");

			using(HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
				string cookieString = response.Headers.Get("Set-Cookie");
				// 备用域: "http://www.yiyaows.cn"
                // "http://www.wenhuakxjyty.cn"
				CookieCollection cc = CookiesHelper.String2CookieCollection(cookieString, domain);
				bool hasJSESSIONID = false;
				foreach(Cookie cookie in cc) {
					if(cookie.Name == "Expires") {
						continue;
					}
					if(cookie.Name == "JSESSIONID") {
						hasJSESSIONID = true;
					}
					Info.Cookies.Add(cookie);
				}
				if(!hasJSESSIONID) {
					throw new Exception("antispiderShowVerify");
				}
				using(StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("gb2312"))) {
					Info.Html = sr.ReadToEnd();
				}
			}
			BuildOriginalUrls();
		}

        /// <summary>
        /// 下载
        /// </summary>
        /// <returns></returns>
        public int Download(PageType type) {
            int result;
            string rootFolder = @"D:\ysm\";
            string lastFolder = Info.Bookinfo.Replace("\\", "、")
                                             .Replace("/", "、")
                                             .Replace(":", "：")
                                             .Replace("*", "·")
                                             .Replace("?", "？")
                                             .Replace("\"", "＂")
                                             .Replace("<", "〈")
                                             .Replace(">", "〉")
                                             .Replace("|", "｜");
            if(type == PageType.Text) {
                result = ImageDownload.GetMainImage(Info.BeginPageNum, Path.Combine(rootFolder, lastFolder), Info);
            } else {
                result = ImageDownload.GetImage(Info.BeginPageNum, Path.Combine(rootFolder, lastFolder), Info, type);
            }
            return result;
        }

        /// <summary>
        /// 停止下载
        /// </summary>
        public void Stop() {
            ImageDownload.Stop = true;
        }

		/// <summary>
		/// 通过对咨询页的解析，生成当前咨询页的所有图片原始链接
		/// </summary>
		/// <returns></returns>
		void BuildOriginalUrls() {
			MemoryStream stream = new MemoryStream(System.Text.Encoding.GetEncoding("gb2312").GetBytes(Info.Html));
			HtmlDocument doc = new HtmlDocument();
			doc.Load(stream);
            HtmlNode titldNode = doc.DocumentNode.SelectSingleNode("//title");
            Info.Bookinfo = doc.DocumentNode.SelectNodes("//div[@id='bookinfo']").FirstOrDefault().InnerText;

			string[] varArr = { "ssNo", "did", "var str", "jpgRange" };
			Dictionary<string, string> dirParam = new Dictionary<string, string>();
			foreach(HtmlNode node in doc.DocumentNode.SelectNodes("//script")) {
				string script = node.InnerText;
				if(script.Contains("ssNo")) {
					string[] scriptArr = script.Split('\n');
					foreach(string scriptLine in scriptArr) {
						foreach(var variable in varArr) {
							if(scriptLine.Trim('\r').Trim('\n').Trim().StartsWith(variable)) {
								var param = scriptLine.Trim('\r').Trim('\n').Trim(' ').Split('=');
								if(param.Length == 2) {
									if(param[0].Trim() == "jpgRange") {
										string[] pagePer = param[1].Trim().Trim(';').Trim('"').Split('-');
										if(pagePer.Length == 2) {
											Info.BeginPageNum = Convert.ToInt32(pagePer[0].Trim());
											dirParam.Add("spage", Info.BeginPageNum.ToString());
											Info.EndPageNum = Convert.ToInt32(pagePer[1].Trim());
											dirParam.Add("epage", Info.EndPageNum.ToString());
										}
									} else {
										if(param[0].Trim().StartsWith("var")) {
											param[0] = param[0].Trim().Substring(3).Trim();
										}
										dirParam.Add(param[0].Trim(), param[1].Trim().Trim(';').Trim('"'));
									}
								}
							}
						}
					}
				}
			}
			int imageCount = Info.EndPageNum - Info.BeginPageNum + 1;
			string[] imageUrlArr = new string[imageCount];

            //Info.ImgOriginalUrlTemp = string.Format("http://www.wenhuakxjyty.cn/n/{0}{1}?.&uf=ssr&zoom={2}", dirParam["str"], "{Temp:0}", ZoomHelper.Zoom);
            Info.ImgOriginalUrlTemp = string.Format("{0}/{1}{2}?.&uf=ssr&zoom={3}", domain, dirParam["str"].TrimStart('/'), "{Temp:0}", ZoomHelper.Zoom);
			for(int i = 0; i < imageCount; i++) {
				string spageString = string.Format("{0:000000}", Info.BeginPageNum + i);
                //string imageUrl = string.Format("http://www.wenhuakxjyty.cn/n/{0}{1}?.&uf=ssr&zoom={2}", dirParam["str"], spageString, ZoomHelper.Zoom);
                string imageUrl = string.Format("{0}/{1}{2}?.&uf=ssr&zoom={3}", domain, dirParam["str"].TrimStart('/'), spageString, ZoomHelper.Zoom);
				imageUrlArr[i] = imageUrl;
			}

			Info.ImgOriginalUrls = imageUrlArr;
		}
	}
}
